package com.plian.system.controller.fr.procurement;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.plian.Tools.*;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.LogOperation;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.Resubmit;
import com.plian.system.dto.fr.procurement.MaterialProcurementDTO;
import com.plian.system.entity.fr.procurement.MaterialProcurement;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.fr.procurement.IMaterialProcurementService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.fr.procurement.MaterialProcurementVO;
import com.plian.system.vo.fr.procurement.ProcurementSummaryVO;
import com.plian.system.vo.report.ReportReturnVO;
import com.plian.system.wrapper.fr.procurement.MaterialProcurementWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * 控制器
 *
 * @author
 * @since 2019-09-27
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("api/materialprocurement")
@Api(value = "大宗物资采购管理", tags = "大宗物资采购管理接口")
public class MaterialProcurementController extends BaseController {

	private IMaterialProcurementService materialProcurementService;

	private FormWorkflowService formWorkflowService;

	private MaterialProcurementWrapper materialProcurementWrapper;

	/**
	 * 详情
	 */
	@PostMapping("/detail")
	public R<MaterialProcurementVO> detail(@RequestBody MaterialProcurement materialProcurement) {
		MaterialProcurement detail = materialProcurementService.getOne(Condition.getQueryWrapper(materialProcurement));
		MaterialProcurementVO materialProcurementVO = materialProcurementWrapper.entityToVO(detail);
		return materialProcurementService.getDetailObj(materialProcurementVO);
	}

	/**
	 * 分页
	 */
	@PostMapping("/list")
	public ListResult<MaterialProcurementVO> list(@RequestBody Query query) {
		return materialProcurementService.list(query);
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@Resubmit(delaySeconds = 0)
	@LogOperation("大宗物资采购管理-提交")
	public ObjResult submit(@Valid @RequestBody MaterialProcurement materialProcurement) {
//		String checkMessage = materialProcurementService.checkMonth(materialProcurement);
//		if (StringUtil.isNotBlank(checkMessage)){
//			return new ObjResult(CustomCode.builder().message(checkMessage).code(1999).success(false).build());
//		}

		boolean result = materialProcurementService.submit(materialProcurement);
		HashMap<String, Object> processVariable = new HashMap<>();
		formWorkflowService.startProcessAndSimulate(String.valueOf(materialProcurement.getId()),materialProcurement.getFormType(),processVariable);

		return result ? new ObjResult(CommonCode.SUCCESS) : new ObjResult(CommonCode.FAIL);
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@LogOperation("大宗物资采购管理-删除")
	public ObjResult remove(@RequestBody PageData pd) {
		List<String> ids = (List<String>)pd.get("ids");
		return materialProcurementService.deleteLogic(Func.toLongList(StringUtils.join(ids, StringPool.COMMA)))
				? new ObjResult(CommonCode.SUCCESS) : new ObjResult(CommonCode.FAIL);
	}

	/**
	 * 企业工程项目和大宗物资（服务）采购汇总表
	 */
	@PostMapping("/summary")
	public ListResult<PageData> summary(@Valid @RequestBody MaterialProcurementDTO materialProcurementDTO) {
		List<ProcurementSummaryVO> results = materialProcurementService.summary(materialProcurementDTO);
		List<PageData> pageDataList = new ArrayList<>();
		try{
			if (CollectionUtil.isNotEmpty(results)){
				for (ProcurementSummaryVO vo : results){
					PageData pd = new PageData();
					ObjectMapper mapper = new ObjectMapper();
					String json = JSON.toJSONStringWithDateFormat(vo, DateUtil.PATTERN_DATETIME);
					pd.putAll(mapper.readValue(json, new TypeReference<HashMap<String,String>>(){}));
					pageDataList.add(pd);
				}
			}
			ListResult<PageData> listResult = new ListResult<>(CommonCode.SUCCESS);
			listResult.setList(pageDataList);
			return listResult;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
			return new ListResult<>(CommonCode.ERROR);
		}

	}

	/**
	 * 根据type值 确定统计维度 1填报单位 2采购单位 3采购分类 4采购平台 5采购分类
	 */
	@PostMapping("/typeSummary")
	public ObjResult typeSummary(@RequestBody MaterialProcurementDTO materialProcurementDTO) {
		ObjResult objResult;
		try {
			ReportReturnVO reportReturnVO = materialProcurementService.typeSummary(materialProcurementDTO);
			objResult = new ObjResult(CommonCode.SUCCESS);
			if (Optional.ofNullable(reportReturnVO).isPresent()){
				PageData pd = new PageData();
				pd.put("grids", reportReturnVO.getGrids());
				objResult.setPageData(pd);
			}
		}catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
			objResult = new ObjResult(CommonCode.ERROR);
			return objResult;
		}

		return objResult;
	}

	/**
	 * 生成excel文件,列表明细导出
	 * @param query
	 * @return
	 */
	@PostMapping("/exportDetail")
	public ObjResult exportDetail(@RequestBody Query query){
		PageData pd = new PageData();
		pd.put("key", materialProcurementService.exportDetail(query));
		ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
		objResult.setPageData(pd);
		return objResult;
	}

	/**
	 * 下载excel文件 并删除
	 * @param key
	 * @param response
	 * @param os
	 */
	@GetMapping("/download/{key}")
//	@PassToken
	public void download(@PathVariable String key, HttpServletResponse response, OutputStream os){
		materialProcurementService.download(key, response, os);
	}

	/**
	 * 模板文件下载
	 * @param response
	 * @param os
	 */
	@GetMapping("/exportTemplateExcel")
//	@PassToken
	@ApiOperation(value = "模板文件下载", notes = "模板文件下载")
	public void exportTemplateExcel(HttpServletResponse response, OutputStream os){
		materialProcurementService.exportTemplateExcel(response, os);
	}

	/**
	 * 覆盖导入 根据年度、采购企业名称 采购项目覆盖或新增
	 */
	@PostMapping("/excelCoverImport")
	@ApiOperation(value = "覆盖导入", notes = "覆盖导入")
	@LogOperation("大宗物资采购管理-导入")
	public ObjResult excelCoverImport(@RequestParam("file") MultipartFile multipartFile) throws IOException {
		String progressId = TokenUtil.getTokenUserId() + "_"+System.currentTimeMillis();
		CacheUtil.put("progress","progress",progressId + "#half:hour",0);
		InputStream inputStream = multipartFile.getInputStream();
		materialProcurementService.importExcel(progressId, inputStream);
		ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
		PageData pd = new PageData();
		pd.put("progressId", progressId);
		objResult.setPageData(pd);
		return objResult;
	}

	/**
	 * 导入进度查看
	 */
	@GetMapping("/progress/{progressId}")
	@ApiOperation(value = "导入进度查看", notes = "导入进度查看")
	public ObjResult progress(@PathVariable String progressId){
		Object data = CacheUtil.get("progress", "progress", progressId + "#half:hour");
		if(data != null && data instanceof String){
			if ("导入成功".equals(data)){
				ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
				PageData pd = new PageData();
				pd.put("data", 200);
				objResult.setPageData(pd);
				return objResult;
			}
			return new ObjResult(CustomCode.builder().message((String)data).code(1000).success(false).build());
		}
		ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
		PageData pd = new PageData();
		pd.put("data", data);
		objResult.setPageData(pd);
		return objResult;
	}


}
